import React, { useState, useEffect, useMemo, useCallback } from 'react';
import {
  Tree,
  Badge,
  Progress,
  Space,
  Typography,
  Tag,
  Tooltip,
  Button,
  Dropdown,
  Menu,
  Input,
  message,
  Spin,
} from 'antd';
import {
  FolderOutlined,
  FolderOpenOutlined,
  FileOutlined,
  BarChartOutlined,
  EyeOutlined,
  EditOutlined,
  SearchOutlined,
  FilterOutlined,
  DownOutlined,
  RightOutlined,
} from '@ant-design/icons';
import type { DataNode, EventDataNode } from 'antd/es/tree';
import type { TreeNode, TelemetryPoint, TreeNodeStats } from '../types/telemetry';
import { FileTreeBuilder } from '../utils/fileTreeBuilder';

const { Text } = Typography;
const { Search } = Input;

export interface TelemetryTreeProps {
  data: TreeNode;
  loading?: boolean;
  onNodeClick?: (node: TreeNode) => void;
  onPointSelect?: (point: TelemetryPoint) => void;
  onPointEdit?: (point: TelemetryPoint) => void;
  selectedKeys?: string[];
  expandedKeys?: string[];
  onExpand?: (expandedKeys: string[]) => void;
  onSelect?: (selectedKeys: string[], info: { node: EventDataNode<TreeNode> }) => void;
  showStats?: boolean;
  searchable?: boolean;
  height?: number | string;
}

const TelemetryTree: React.FC<TelemetryTreeProps> = ({
  data,
  loading = false,
  onNodeClick,
  onPointSelect,
  onPointEdit,
  selectedKeys = [],
  expandedKeys = [],
  onExpand,
  onSelect,
  showStats = true,
  searchable = true,
  height = '600px',
}) => {
  const [searchTerm, setSearchTerm] = useState('');
  const [highlightedKeys, setHighlightedKeys] = useState<string[]>([]);
  const [treeData, setTreeData] = useState<DataNode[]>([]);

  // 搜索高亮处理
  useEffect(() => {
    if (searchTerm.trim()) {
      const matches = FileTreeBuilder.searchNodes(data, searchTerm);
      setHighlightedKeys(matches);

      // 自动展开包含匹配结果的节点
      const expandKeys = new Set<string>();
      matches.forEach(key => {
        const path = FileTreeBuilder.getNodePath(data, key);
        path.forEach(node => {
          if (node.key !== 'root') {
            expandKeys.add(node.key);
          }
        });
      });

      if (onExpand && expandKeys.size > 0) {
        onExpand(Array.from(expandKeys));
      }
    } else {
      setHighlightedKeys([]);
    }
  }, [searchTerm, data, onExpand]);

  // 转换树数据为Ant Design Tree格式
  const convertToTreeData = useCallback((node: TreeNode, parentExpanded = false): DataNode => {
    const isHighlighted = highlightedKeys.includes(node.key);
    const isSelected = selectedKeys.includes(node.key);
    const stats = node.stats ? FileTreeBuilder.calculateAggregatedStats(node) : undefined;

    const nodeTitle = (
      <div
        style={{
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center',
          padding: '2px 0',
          backgroundColor: isHighlighted ? '#e6f7ff' : undefined,
          borderRadius: '4px',
        }}
        onClick={() => onNodeClick?.(node)}
      >
        <Space size="small">
          {node.isLeaf ? (
            <FileOutlined style={{ color: '#1890ff' }} />
          ) : (
            (expandedKeys.includes(node.key) || parentExpanded) ? (
              <FolderOpenOutlined style={{ color: '#faad14' }} />
            ) : (
              <FolderOutlined style={{ color: '#faad14' }} />
            )
          )}
          <Text
            strong={isSelected}
            style={{
              color: isHighlighted ? '#1890ff' : undefined,
              cursor: 'pointer',
            }}
          >
            {node.title}
          </Text>
          {node.telemetryPoints && node.telemetryPoints.length > 0 && (
            <Tag color="blue">
              {node.telemetryPoints.length}
            </Tag>
          )}
        </Space>

        {showStats && stats && stats.total > 0 && (
          <Space size="small" onClick={(e) => e.stopPropagation()}>
            <Badge count={stats.total} showZero color="#1890ff" />
            {stats.notAnalyzed > 0 && (
              <Tooltip title="待分析">
                <Badge count={stats.notAnalyzed} showZero color="#faad14" />
              </Tooltip>
            )}
            {stats.analyzed > 0 && (
              <Tooltip title="已分析">
                <Badge count={stats.analyzed} showZero color="#52c41a" />
              </Tooltip>
            )}
          </Space>
        )}
      </div>
    );

    const treeNode: DataNode = {
      title: nodeTitle,
      key: node.key,
      isLeaf: node.isLeaf,
      children: node.children?.map(child => convertToTreeData(child, expandedKeys.includes(node.key))),
    };

    return treeNode;
  }, [selectedKeys, expandedKeys, highlightedKeys, showStats, onNodeClick]);

  // 监听数据变化，转换树数据
  useEffect(() => {
    if (data) {
      setTreeData([convertToTreeData(data)]);
    }
  }, [data, convertToTreeData]);

  // 处理节点选择
  const handleSelect = useCallback((
    selectedKeys: any[],
    info: { node: EventDataNode<TreeNode>; selected: boolean; selectedNodes: TreeNode[]; }
  ) => {
    const { node } = info;

    // 如果是叶子节点且包含遥测点数据
    if (node.isLeaf && node.telemetryPoints && node.telemetryPoints.length > 0) {
      const point = node.telemetryPoints[0];
      onPointSelect?.(point);
    }

    onSelect?.(selectedKeys as string[], info as any);
  }, [onPointSelect, onSelect]);

  // 处理节点展开
  const handleExpand = useCallback((expandedKeys: any[], info: any) => {
    onExpand?.(expandedKeys as string[]);
  }, [onExpand]);

  // 右键菜单
  const handleRightClick = useCallback(({ node }: { node: any }) => {
    const handleMenuClick = ({ key }: { key: string }) => {
      switch (key) {
        case 'view':
          onNodeClick?.(node);
          break;
        case 'expand':
          if (node.children) {
            const keysToExpand = [node.key];
            // 递归展开所有子节点
            const expandAllChildren = (children: any[]) => {
              children.forEach((child: any) => {
                keysToExpand.push(child.key);
                if (child.children) {
                  expandAllChildren(child.children);
                }
              });
            };
            expandAllChildren(node.children);
            onExpand?.(Array.from(new Set([...expandedKeys, ...keysToExpand])));
          }
          break;
        case 'collapse':
          if (node.children) {
            const keysToCollapse = [node.key];
            // 递归折叠所有子节点
            const collapseAllChildren = (children: any[]) => {
              children.forEach((child: any) => {
                keysToCollapse.push(child.key);
                if (child.children) {
                  collapseAllChildren(child.children);
                }
              });
            };
            collapseAllChildren(node.children);
            const newExpandedKeys = expandedKeys.filter(key => !keysToCollapse.includes(key));
            onExpand?.(newExpandedKeys);
          }
          break;
        default:
          break;
      }
    };

    const contextMenu = (
      <Menu onClick={handleMenuClick}>
        <Menu.Item key="view" icon={<EyeOutlined />}>
          查看详情
        </Menu.Item>
        {node.children && (
          <>
            <Menu.Item key="expand" icon={<DownOutlined />}>
              展开所有子节点
            </Menu.Item>
            <Menu.Item key="collapse" icon={<RightOutlined />}>
              折叠所有子节点
            </Menu.Item>
          </>
        )}
      </Menu>
    );

    // 这里可以显示右键菜单，暂时用console.log
    console.log('Right click on node:', node);
  }, [expandedKeys, onExpand, onNodeClick]);

  // 批量操作菜单
  const batchActionsMenu = (
    <Menu>
      <Menu.Item key="expandAll" icon={<DownOutlined />}>
        展开所有节点
      </Menu.Item>
      <Menu.Item key="collapseAll" icon={<RightOutlined />}>
        折叠所有节点
      </Menu.Item>
      <Menu.Divider />
      <Menu.Item key="expandFirstLevel" icon={<FolderOpenOutlined />}>
        展开第一级
      </Menu.Item>
    </Menu>
  );

  return (
    <div style={{ height, display: 'flex', flexDirection: 'column' }}>
      {/* 工具栏 */}
      <div style={{ marginBottom: '16px', display: 'flex', gap: '8px', alignItems: 'center' }}>
        {searchable && (
          <Search
            placeholder="搜索目录或遥测点..."
            allowClear
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            style={{ flex: 1 }}
            prefix={<SearchOutlined />}
          />
        )}
        <Dropdown overlay={batchActionsMenu} trigger={['click']}>
          <Button icon={<FilterOutlined />}>
            批量操作 <DownOutlined />
          </Button>
        </Dropdown>
      </div>

      {/* 统计信息 */}
      {showStats && data.stats && (
        <div style={{ marginBottom: '16px', padding: '12px', backgroundColor: '#fafafa', borderRadius: '6px' }}>
          <Space size="large">
            <div>
              <Text type="secondary">总遥测点</Text>
              <div style={{ fontSize: '18px', fontWeight: 'bold', color: '#1890ff' }}>
                {data.stats.total}
              </div>
            </div>
            <div>
              <Text type="secondary">已分析</Text>
              <div style={{ fontSize: '18px', fontWeight: 'bold', color: '#52c41a' }}>
                {data.stats.analyzed}
              </div>
            </div>
            <div>
              <Text type="secondary">待分析</Text>
              <div style={{ fontSize: '18px', fontWeight: 'bold', color: '#faad14' }}>
                {data.stats.notAnalyzed}
              </div>
            </div>
            <div style={{ flex: 1 }}>
              <Text type="secondary">分析进度</Text>
              <Progress
                percent={data.stats.analysisProgress}
                size="small"
                strokeColor={{
                  '0%': '#108ee9',
                  '100%': '#52c41a',
                }}
              />
            </div>
          </Space>
        </div>
      )}

      {/* 树形组件 */}
      <div style={{ flex: 1, overflow: 'auto' }}>
        {loading ? (
          <div style={{
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center',
            height: typeof height === 'number' ? height - 120 : '400px'
          }}>
            <Spin size="large" />
          </div>
        ) : (
          <Tree
            showLine
            showIcon={false}
            blockNode
            treeData={treeData as any[]}
            selectedKeys={selectedKeys as any[]}
            expandedKeys={expandedKeys as any[]}
            onExpand={handleExpand}
            onSelect={handleSelect}
            onRightClick={handleRightClick}
            virtual
            height={typeof height === 'number' ? height - 120 : undefined}
          />
        )}
      </div>

      {/* 搜索结果提示 */}
      {searchTerm && highlightedKeys.length > 0 && (
        <div style={{ marginTop: '8px', padding: '8px', backgroundColor: '#e6f7ff', borderRadius: '4px' }}>
          <Text type="secondary">
            找到 {highlightedKeys.length} 个匹配结果
          </Text>
        </div>
      )}
    </div>
  );
};

export default TelemetryTree;